package com.mzj.saas.mservice.smartlock.service.yaluete;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.MD5Util;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.SSLNetProvider;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.lock.Repository.SmartLockEmpowerRepository;
import com.mzj.saas.mservice.lock.Repository.SmartLockRepository;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockEmpower;
import com.mzj.saas.mservice.lockManager.entity.SmartLockBrand;
import com.mzj.saas.mservice.lockManager.repository.SmartLockBrandRepository;
import com.mzj.saas.mservice.smartlock.vo.DynamicPasswordVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import com.mzj.saas.mservice.smartlock.vo.yaluete.YltAuthorizationRecordVO;
import com.mzj.saas.mservice.smartlock.vo.yaluete.YltAuthorizationVO;
import com.mzj.saas.mservice.smartlock.vo.yaluete.YltTokenResponseVO;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 亚略特-智能锁接口
 *
 * @author shun
 * @createDate: 2021年6月26日 下午3:10:56
 * @version: 1.0
 *
 */
@Service
public class SmartLockYltService {

	private static final Logger log = LoggerFactory.getLogger(SmartLockYltService.class);
	// 工厂那边配置的，不同商户配置不同推送地址，程序无法指定
	@Value("${yaluete.lock.callback.url}")
	private String xizhaoLockCallbackUrl;
	// 商户编号
	@Value("${yaluete.lock.fnumber}")
	private String fnumber;

	@Autowired
	private SSLNetProvider httpClient;
	@Autowired
	private RedisService redisService;
	@Autowired
	private SmartLockRepository smartLockRepository;
	@Autowired
	private SmartLockBrandRepository smartLockBrandRepository;
	@Autowired
	private SmartLockEmpowerRepository smartLockEmpowerRepository;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	private static final String sql = "SELECT a.user_name FROM  saas_smart_lock_auth a\n" +
			"LEFT JOIN saas_smart_lock_pwd p on p .lock_auth_id= a.id \n" +
			"LEFT JOIN saas_smart_lock_card c on c.lock_auth_id= a.id \n" +
			"LEFT JOIN saas_smart_lock_ble b on b.lock_auth_id= a.id \n" +
			"LEFT JOIN saas_smart_lock_fingerprint f on f.lock_auth_id= a.id \n" +
			"where (p.f_app_user_id=? or c.f_app_user_id=? or b.f_app_user_id=? or f.f_app_user_id=? )  limit 1 ";

	/**
	 * 生成token
	 *
	 * @return
	 * @author shun
	 * @date 2021年9月13日
	 * 密钥生成token
	 */
	public YltTokenResponseVO generateToken(SmartLockBrand brand) {
		String md5Pwd = MD5Util.encryption(brand.getSercret());
		Map<String, String> map = new HashMap<>();
		map.put("fName", brand.getSid());
		map.put("fPassWord", md5Pwd);
		//用户类型，默认2
		map.put("fUserType", "2");
		String resultStr = httpClient.httpPostYlt(brand.getApiUrl() + "api/login", JSON.toJSONString(map), null);
		JSONObject result = JSONObject.parseObject(resultStr);
		String code = result.get("code").toString();

		YltTokenResponseVO vo = new YltTokenResponseVO();
		vo.setCode(code);

		if ("0".equals(code)) {
			JSONObject data = result.getJSONObject("data");
			if (data != null) {
				String token = data.get("token").toString();
				vo.setToken(token);
				return vo;
			}
		} else {
			String message = result.get("message").toString();
			vo.setMessage(message);
			return vo;
		}
		return null;
	}

	/**
	 * 获取token
	 *
	 * @return
	 * @author shun
	 * @date 2021年9月13日
	 */
	public String getLoginToken(SmartLockBrand brand) {
		String token = redisService.getYltToken();
		if (StringUtils.isEmpty(token)) {
			YltTokenResponseVO vo = generateToken(brand);
			if ("0".equals(vo.getCode())) {
				redisService.putYltToken(vo.getToken());
				return vo.getToken();
			}

			log.info("SmartLockYltService getLoginToken, result={}", JSON.toJSONString(vo));
		}
		return token;
	}

	/**
	 * 注册-锁绑定商户
	 *
	 * @param imei
	 *            设备MAC编号
	 * @param brandId
	 *            品牌ID
	 * @return
	 * @author shun
	 * @date 2021年9月15日
	 */
	public ResultBean<String> merchantinfoBindLock(String imei, Long brandId) {
		try {
			log.info("亚略特, 锁绑定商户, imei={}, brandId={}", imei, brandId);
			if (StringUtils.isBlank(imei)) {
				log.info("锁绑定商户, 参数为空, imei={}", imei);
				return ResultBean.failedResultOfParamWithMsg("参数错误");
			}

			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(brandId);
			if (!optional.isPresent()) {
				log.info("设备品牌信息未找, brandId={}", brandId);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}
			String url = brand.getApiUrl() + "api/lockmerchant/merchantinfoBindLock";

			// 获取token
			String token = getLoginToken(brand);

			// 请求消息体
			Map<String, String> map = new HashMap<>();
			map.put("fLockMAC", imei);
			map.put("fNumber", fnumber);

			// 接口调用
			log.info("body={}", JSON.toJSONString(map));
			String resultStr = httpClient.httpPostYlt(url, JSON.toJSONString(map), token);
			log.info("亚略特, 锁绑定商户, map={}, resultStr={}", JSON.toJSONString(map), JSON.toJSONString(resultStr));
			if ("HTTP Status 404".contains(resultStr)) {
				return ResultBean.failedResultWithMsg("设备异常, 稍后重试");
			}
			JSONObject result = JSONObject.parseObject(resultStr);
			String code = result.get("code").toString();
			if (!"0".equals(code)) {
				return ResultBean.failedResultWithMsg(result.getString("message"));
			}

			// 亚略特没有sn, 可以直接通过imei操作业务
			return ResultBean.successfulResult(imei);
		} catch (Exception e) {
			log.error("锁绑定商户异常" + e.getMessage(), e);
			return ResultBean.failedResultWithMsg("设备异常, 稍后重试");
		}
	}

	/**
	 * 解绑商户 注：解绑前请保证锁无有效授权（可通过查询锁授权接口查询，取消授权接口取消锁授权）。否则调用此接口会报错。
	 *
	 * @param imei
	 *            设备MAC编号
	 * @param brandId
	 *            品牌ID
	 * @return
	 * @author shun
	 * @date 2021年9月15日
	 */
	public ResultBean<String>  merchantinfoUnBindLock(String imei, Long brandId) {
		try {
			log.info("亚略特, 解绑商户, imei={}, brandId={}", imei, brandId);
			if (StringUtils.isBlank(imei)) {
				log.info("解绑商户, 参数为空, imei={}", imei);
				return ResultBean.failedResultOfParamWithMsg("参数错误");
			}

			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(brandId);
			if (!optional.isPresent()) {
				log.info("设备品牌信息未找, brandId={}", brandId);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}
			String url = brand.getApiUrl() + "api/lockmerchant/merchantinfoUnBindLock";
			// 获取token
			String token = getLoginToken(brand);

			// 查看锁授权情况，如果有未取消的授权，需要先取消授权，才能解绑
			ResultBean<List<YltAuthorizationRecordVO>> authListResult = select(imei, brandId);
			if (!authListResult.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
				return ResultBean.failedResultWithMsg(authListResult.getMsg());
			}

			if (authListResult.getResultData() != null) {
				List<YltAuthorizationRecordVO> voList = authListResult.getResultData();
				if (voList.size() > 0) {
					// 清除锁所有授权
					SmartLockVO lockVO = new SmartLockVO();
					lockVO.setSn(imei);
					ResultBean<String> resultBean = deauthorize(lockVO, brandId, 2);
					if (!resultBean.getCode().equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
						return resultBean;
					}
				}
			}

			// 请求消息体
			Map<String, String> map = new HashMap<>();
			map.put("fLockMAC", imei);

			// 接口调用
			log.info("body={}", JSON.toJSONString(map));
			String resultStr = httpClient.httpPostYlt(url, JSON.toJSONString(map), token);
			log.info("亚略特, 解绑商户, map={}, resultStr={}", JSON.toJSONString(map), JSON.toJSONString(resultStr));
			if ("HTTP Status 404".contains(resultStr)) {
				return ResultBean.failedResultWithMsg("设备异常, 稍后重试");
			}
			JSONObject result = JSONObject.parseObject(resultStr);
			String code = result.get("code").toString();
			if (!"0".equals(code)) {
				return ResultBean.failedResultWithMsg(result.getString("message"));
			}

			return ResultBean.successfulResult(imei);
		} catch (Exception e) {
			log.error("解绑商户异常" + e.getMessage(), e);
			return ResultBean.failedResultWithMsg("设备异常, 稍后重试");
		}

	}

	/**
	 * 查看锁授权情况
	 *
	 * @param imei
	 *            设备MAC编号
	 * @param brandId
	 *            品牌ID
	 * @return
	 * @author shun
	 * @date 2021年9月15日
	 */
	public ResultBean<List<YltAuthorizationRecordVO>> select(String imei, Long brandId) {
		try {
			log.info("亚略特, 查看锁授权情况, imei={}, brandId={}", imei, brandId);
			if (StringUtils.isBlank(imei)) {
				log.info("查看锁授权情况, 参数为空, imei={}", imei);
				return ResultBean.failedResultOfParamWithMsg("参数错误");
			}

			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(brandId);
			if (!optional.isPresent()) {
				log.info("设备品牌信息未找, brandId={}", brandId);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}
			String url = brand.getApiUrl() + "api/lock/select";
			// 获取token
			String token = getLoginToken(brand);

			// 请求消息体
			Map<String, Object> map = new HashMap<>();
			map.put("fLockMAC", imei);
			map.put("fNumber", fnumber);// 商户编号
			map.put("pageSize", 200);// 每页数量
			map.put("pageNum", 0);// 页码
			//map.put("fSyncFlag", imei);// 是否已经同步到锁:0否;1是;
			map.put("fStatus", "1");// 状态:1启用;2禁用
			//map.put("fBeginDate", imei);// 开始时间
			//map.put("fEndDate", imei);// 结束时间

			// 接口调用
			log.info("body={}", JSON.toJSONString(map));
			String resultStr = httpClient.httpPostYlt(url, JSON.toJSONString(map), token);
			log.info("亚略特, 查看锁授权情况, map={}, resultStr={}", JSON.toJSONString(map), JSON.toJSONString(resultStr));
			JSONObject object = JSONObject.parseObject(resultStr);
			if (!"0".equals(object.get("code"))) {
				return ResultBean.failedResultWithMsg(object.getString("message"));
			}

			JSONObject data = JSONObject.parseObject(object.getString("data"));
			List<YltAuthorizationRecordVO> vod = JSONObject.parseArray(data.getString("AuthorzizationRecord"), YltAuthorizationRecordVO.class);

			return ResultBean.successfulResult(vod);
		} catch (Exception e) {
			log.error("查看锁授权情况异常" + e.getMessage(), e);
			return ResultBean.failedResultWithMsg("设备异常, 稍后重试");
		}
	}

	/**
	 * 开锁授权
	 *
	 * @param brandId
	 * @param
	 * @return
	 * @author shun
	 * @date 2021年9月13日
	 */
	public ResultBean<String> lockAuthorization(Long brandId, SmartLockVO svo) {
		try {
			if (svo.getYltAuth() == null) {
				log.info("开锁授权, 参数为空, YltAuth is null");
				return ResultBean.failedResultOfParamWithMsg("参数为空");
			}
			log.info("亚略特, 开锁授权, YltAuth={}, brandId={}", JSON.toJSONString(svo), brandId);
			List<YltAuthorizationVO> list = new ArrayList<>();
			list.add(svo.getYltAuth());

			for (YltAuthorizationVO vo : list) {
				vo.setfNumber(fnumber);
				if (StringUtils.isEmpty(vo.getfLockMAC()) || StringUtils.isEmpty(vo.getfAppUserID())
						|| StringUtils.isEmpty(vo.getfAppUserID()) || StringUtils.isEmpty(vo.getfBeginDate())
						|| StringUtils.isEmpty(vo.getfEndDate()) || vo.getfOpenByPassword() == null
						|| vo.getfOpenByIDCard() == null || vo.getfOpenByBLE() == null || vo.getfOpenByFinger() == null
						|| vo.getfOpenByICCard() == null || StringUtils.isEmpty(vo.getfAppUserID())) {

					log.info("开锁授权, 参数为空, list={}", JSON.toJSONString(list));
					return ResultBean.failedResultOfParamWithMsg("参数为空");
				}

				if (vo.getfOpenByPassword() == 1 && StringUtils.isEmpty(vo.getfOpenPassword())) {
					log.info("开锁授权, 参数为空, fOpenByPassword={}, fOpenPassword={}", vo.getfOpenByPassword(),
							vo.getfOpenPassword());
					return ResultBean.failedResultOfParamWithMsg("参数为空");
				}

				if (vo.getfOpenByIDCard() == 1 && StringUtils.isEmpty(vo.getfIDCardNumber())) {
					log.info("开锁授权, 参数为空, fOpenByIDCard={}, fIDCardNumber={}", vo.getfOpenByIDCard(),
							vo.getfOpenByIDCard());
					return ResultBean.failedResultOfParamWithMsg("参数为空");
				}

				if (vo.getfOpenByFinger() == 1 && StringUtils.isEmpty(vo.getfFingerFeature())) {
					log.info("开锁授权, 参数为空, fOpenByFinger={}, fFingerFeature={}", vo.getfOpenByFinger(),
							vo.getfFingerFeature());
					return ResultBean.failedResultOfParamWithMsg("参数为空");
				}
			}

			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(brandId);
			if (!optional.isPresent()) {
				log.info("亚略特, 设备品牌信息未找, brandId={}", brandId);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}

			// 获取token
			String token = getLoginToken(brand);

			String resultStr = httpClient.httpPostYlt(brand.getApiUrl() + "api/lock/authorization",
					JSON.toJSONString(list), token);
			log.info("亚略特, 开锁授权指令, result={}", resultStr);

			JSONObject result = JSONObject.parseObject(resultStr);
			String code = result.get("code").toString();
			if (!"0".equals(code)) {
				return ResultBean.failedResultWithMsg(result.getString("message"));
			}
			String data = result.getString("data");

			//写入用户授权表
			empowerUser(svo.getfAppUserID());

			if (data != null) {
				String lockOpenCommands = JSONObject.parseObject(data).getString("lockOpenCommands");

				// 授 权 ID
				JSONArray jsonArray = JSON.parseArray(lockOpenCommands);
				for (Object object : jsonArray) {
					// 授 权 ID
					String authorizationID =  JSONObject.parseObject(object.toString()).getString("fAuthorizationID");
					// 蓝牙配对密码
					String fBLEPassword = JSONObject.parseObject(object.toString()).get("fBLEPassword").toString();
					// 锁蓝牙密码临时存放redis
					redisService.putYltFBLEPassword(authorizationID, fBLEPassword);

					return ResultBean.successfulResult(authorizationID);
				}
			}

			return ResultBean.failedResultOfParamWithMsg(result.get("message").toString());
		} catch (Exception e) {
			log.error("亚略特, 开锁授权异常" + e.getMessage(), e);
			return ResultBean.failedResultOfException();
		}
	}

	/**
	 * 更新开锁授权指令 注：只能更新密码授权(开始时间、结束时间、密码)
	 *
	 * @param lockVO
	 * @param brandId
	 * @return
	 * @author shun
	 * @date 2021年9月14日
	 */
	public ResultBean<String> updateAuthorize(SmartLockVO lockVO, Long brandId) {
		try {
			log.info("亚略特, 更新开锁授权指令, vo={}, brandId={}", JSON.toJSONString(lockVO), brandId);
			// 时间不能为空，如果没变动，可以取以前设置的时间值
			if (StringUtils.isBlank(lockVO.getStartTime()) || StringUtils.isBlank(lockVO.getEndTime())
					|| StringUtils.isEmpty(lockVO.getfAuthorizationID())) {
				log.info("亚略特, 参数错误, startTime={}, endTime={}, fAuthorizationID={}", lockVO.getStartTime(),
						lockVO.getEndTime(), lockVO.getfAuthorizationID());
				return ResultBean.failedResultOfParamWithMsg("参数错误");
			}
			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(brandId);
			if (!optional.isPresent()) {
				log.info("亚略特, 设备品牌信息未找, brandId={}", brandId);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}

			// 获取token
			String token = getLoginToken(brand);

			Map<String, String> paramMap = new HashMap<>();
			// 授权id
			paramMap.put("fAuthorizationID", lockVO.getfAuthorizationID());
			// 开始时间
			paramMap.put("fBeginDate", lockVO.getStartTime());
			// 结束时间
			paramMap.put("fEndDate", lockVO.getEndTime());
			if (StringUtils.isNoneBlank(lockVO.getPassword())) {
				// 授权密码
				paramMap.put("fOpenPassword", lockVO.getPassword());
			}

			String resultStr = httpClient.httpPostYlt(brand.getApiUrl() + "api/lock/updateAuthorize",
					JSON.toJSONString(paramMap), token);
			log.info("亚略特, 更新开锁授权指令, fAuthorizationID={}, result={}", lockVO.getfAuthorizationID(), resultStr);
			JSONObject result = JSONObject.parseObject(resultStr);
			String code = result.get("code").toString();
			//写入用户授权表
			empowerUser(lockVO.getfAppUserID());

			if (!"0".equals(code)) {
				return ResultBean.failedResultWithMsg(result.getString("message"));
			}
			// {"code":"0","message":"SUCCESS"}
			return ResultBean.successfulResult(null);
		} catch (Exception e) {
			log.error("亚略特, 更新开锁授权指令异常" + e.getMessage(), e);
			return ResultBean.failedResultOfException();
		}
	}

	/**
	 * 取消开锁授权指令/清除所有授权
	 *
	 * @param lockVO
	 * @param brandId
	 * @param type
	 *            1取消某授权 2清除锁所有授权
	 * @return
	 * @author shun
	 * @date 2021年9月15日
	 */
	public ResultBean<String> deauthorize(SmartLockVO lockVO, Long brandId, Integer type) {
		try {
			log.info("亚略特, 取消开锁授权指令, vo={}, type={}", JSON.toJSONString(lockVO), type);
			if (StringUtils.isBlank(lockVO.getSn())) {
				log.info("亚略特, 参数错误, sn={}, fAuthorizationID={}", lockVO.getSn(), lockVO.getfAuthorizationID());
				return ResultBean.failedResultOfParamWithMsg("参数错误");
			}

			if ((type == null || type == 1) && StringUtils.isBlank(lockVO.getfAuthorizationID())) {
				log.info("亚略特, 参数错误, sn={}, fAuthorizationID={}", lockVO.getSn(), lockVO.getfAuthorizationID());
				return ResultBean.failedResultOfParamWithMsg("参数错误");
			}

			//获取品牌信息
			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(brandId);
			if (!optional.isPresent()) {
				log.info("亚略特, 设备品牌信息未找, brandId={}", brandId);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			//API接口地址、第三方标识、密钥
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}

			Map<String, String> paramMap = new HashMap<>();

			// 锁 MAC 地址
			paramMap.put("fLockMAC", lockVO.getSn());

			/**
			 * 如果AuthorizationID字段为空且fNumber为空，清除锁所有授权记录
			 */
			if (type == null || type == 1) {
				// 授权id
				paramMap.put("fAuthorizationID", lockVO.getfAuthorizationID());
				// 商户编号
				paramMap.put("fNumber", fnumber);
			}

			// 备注
			// paramMap.put("fDescription", "");
			// 平台 ID
			// paramMap.put("fAppID", "");

			// 获取token 从亚略特厂家获取token
			String token = getLoginToken(brand);

			String resultStr = httpClient.httpPostYlt(brand.getApiUrl() + "api/lock/deauthorize",
					JSON.toJSONString(paramMap), token);

			log.info("亚略特, 取消开锁授权指令, sn={}, result={}", lockVO.getSn(), resultStr);
			JSONObject result = JSONObject.parseObject(resultStr);
			String code = result.get("code").toString();
			if (!"0".equals(code)) {
				return ResultBean.failedResultWithMsg(result.getString("message"));
			}
			// {"code":"0","message":"SUCCESS"}
			return ResultBean.successfulResult(null);
		} catch (Exception e) {
			log.error("亚略特, 取消开锁授权指令异常" + e.getMessage(), e);
			return ResultBean.failedResultOfException();
		}
	}

	/**
	 * 动态密码-获取紧急密码
	 *
	 * @param
	 * @param brandId
	 * @return
	 * @author shun
	 * @date 2021年9月14日
	 */
	public ResultBean<List<DynamicPasswordVO>> getUrgentPassword(String mac, Long brandId) {
		try {
			log.info("亚略特, 获取紧急密码, mac={}", mac);
			if (StringUtils.isBlank(mac)) {
				log.info("亚略特, 参数错误, mac={}", mac);
				return ResultBean.failedResultOfParamWithMsg("参数错误");
			}

			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(brandId);
			if (!optional.isPresent()) {
				log.info("亚略特, 设备品牌信息未找, brandId={}", brandId);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}

			Map<String, String> paramMap = new HashMap<>();

			// 锁 MAC 地址
			paramMap.put("fLockMAC", mac);

			// 获取token
			String token = getLoginToken(brand);

			String resultStr = httpClient.httpPostYlt(brand.getApiUrl() + "api/passwordPool/getUrgentPassword",
					JSON.toJSONString(paramMap), token);
			log.info("亚略特, 获取紧急密码, result={}", resultStr);

			JSONObject result = JSONObject.parseObject(resultStr);
			int code = Integer.parseInt(result.get("code").toString());
			if (code != 0) {
				return ResultBean.failedResultWithMsg(result.getString("message"));
			}
			JSONObject object = result.getJSONObject("data");
			List<DynamicPasswordVO> dataArray = new ArrayList<>();
			DynamicPasswordVO passwordVO = new DynamicPasswordVO();
			passwordVO.setPassword(object.getString("fPassword"));
			dataArray.add(passwordVO);
			return ResultBean.successfulResult(dataArray);
		} catch (Exception e) {
			log.error("亚略特, 获取紧急密码异常" + e.getMessage(), e);
			return ResultBean.failedResultOfException();
		}
	}

	/**
	 * 查询智能锁品牌信息
	 * @param mac
	 * @return
	 * @author shun
	 * @date 2021年9月29日
	 */
	public SmartLockBrand findLockBrandId(String mac){
		SmartLock lock = smartLockRepository.findByMac(mac);
		if(lock == null){
			return null;
		}

		Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(lock.getBrandId());
		if (!optional.isPresent()) {
			log.info("亚略特, 设备品牌信息未找, brandId={}", lock.getBrandId());
			return null;
		}
		return optional.get();
	}

	/**
	 * 写入用户授权表
	 * @param fAppUserID
	 */
	public void empowerUser(String fAppUserID) {
		List<SmartLockEmpower> lockEmpower = smartLockEmpowerRepository.findByFAppUserId(fAppUserID);
		String name=null;
		try {
			name = jdbcTemplate.queryForObject(sql, String.class, fAppUserID, fAppUserID, fAppUserID, fAppUserID);
		}catch (Exception e){
			log.error("查询不到授权人名字： userName={}",name);
		}
		if (lockEmpower.isEmpty()){
			SmartLockEmpower smartLockEmpower = new SmartLockEmpower();
			smartLockEmpower.setfAppUserId(fAppUserID); // 亚略特授权用户id
			smartLockEmpower.setUserName(name); // 用户授权id
			smartLockEmpower.setDateTime(new Date()); // 创建时间
			smartLockEmpowerRepository.save(smartLockEmpower);
		}else {
			SmartLockEmpower smartLockEmpower = lockEmpower.get(0);
			smartLockEmpower.setUserName(name);
			smartLockEmpowerRepository.save(smartLockEmpower);
		}
	}

	/**
	 * 修改商户信息，增加推送地址
	 * @param fNumber
	 * @param fPlatformUrl
	 * @return
	 * @author shun
	 * @date 2022年6月30日
	 */
	public ResultBean<String> updateMerchantinfoList(String fNumber, String fPlatformUrl) {
		try {
			log.info("亚略特, 修改商户信息, 设置推送地址, fNumber={}, callbackUrl={}", fNumber, fPlatformUrl);

			// 默认亚略特
			Optional<SmartLockBrand> optional = smartLockBrandRepository.findById(3l);
			if (!optional.isPresent()) {
				log.info("设备品牌信息未找, brandId={}", 3);
				return ResultBean.failedResultOfParamWithMsg("设备品牌信息未找到");
			}

			SmartLockBrand brand = optional.get();
			if (StringUtils.isEmpty(brand.getApiUrl()) || StringUtils.isEmpty(brand.getSid())
					|| StringUtils.isEmpty(brand.getSercret())) {
				log.info("亚略特, 设备品牌接口参数为空, url={}, sid={}, sercret={}", brand.getApiUrl(), brand.getSid(),
						brand.getSercret());
				return ResultBean.failedResultOfParamWithMsg("硬件接口参数为空");
			}
			String url = brand.getApiUrl() + "api/merchantinfo/updateMerchantinfoList";
			// 获取token
			String token = getLoginToken(brand);

			// 请求消息体
			Map<String, Object> map = new HashMap<>();
			map.put("fNumber", fNumber);
			map.put("fEnablePush", 1);
			map.put("fPlatformUrl", fPlatformUrl);
			map.put("fPushUrlSuffix", "/api/device/ylt/log");

			// 接口调用
			log.info("body={}", JSON.toJSONString(map));
			String resultStr = httpClient.httpPostYlt(url, JSON.toJSONString(map), token);
			log.info("亚略特, 修改商户信息, 设置推送地址, map={}, resultStr={}", JSON.toJSONString(map), JSON.toJSONString(resultStr));
			if ("HTTP Status 404".contains(resultStr)) {
				return ResultBean.failedResultWithMsg("设备异常, 稍后重试");
			}
			JSONObject result = JSONObject.parseObject(resultStr);
			String code = result.get("code").toString();
			if (!"0".equals(code)) {
				return ResultBean.failedResultWithMsg(result.getString("message"));
			}

			return ResultBean.successfulResult(fNumber);
		} catch (Exception e) {
			log.error("解绑商户异常" + e.getMessage(), e);
			return ResultBean.failedResultWithMsg("设备异常, 稍后重试");
		}

	}
}
